import useDictStore from '@/store/modules/dict'
import { getDicts } from '@/api/system/dict/data'
import { $dic } from '@/api/dic.js'

/**
 * 获取字典数据
 */
export function useDict(...args) {
  const res = ref({})
  return (() => {
    args.forEach((dictType, index) => {
      res.value[dictType] = []
      const dicts = useDictStore().getDict(dictType)
      if (dicts) {
        res.value[dictType] = dicts
      } else {
        getDicts(dictType).then((resp) => {
          res.value[dictType] = resp.data.map((p) => ({
            label: p.dictLabel,
            value: p.dictValue,
            elTagType: p.listClass,
            elTagClass: p.cssClass,
          }))

          useDictStore().setDict(dictType, res.value[dictType])
        })
      }
    })
    return toRefs(res.value)
  })()
}

/**
 * 获取动态字典数据
 */
export function useApiDict(...args) {
  const res = ref({})
  for (let dictType of args) {
    res.value[dictType] = []
    const dicts = useDictStore().getDict(dictType)
    if (dicts) {
      res.value[dictType] = dicts
      continue
    }

    // 通过接口获取数据

    // 没有接口
    if (!$dic[dictType]) {
      continue
    }

    $dic[dictType]().then((resp) => {
      res.value[dictType] = resp.data

      useDictStore().setDict(dictType, res.value[dictType])
    })
  }

  return toRefs(res.value)
}

/**
 * 更新动态字典数据
 */
export function updateApiDict(dictType) {
  const res = ref({})
  return $dic[dictType]().then((resp) => {
    res.value[dictType] = resp.data

    useDictStore().setDict(dictType, res.value[dictType])
    return resp
  })
}
